package com.wss.lsl.alading.interceptor.session;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SessionInterceptor implements HandlerInterceptor {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		String[] noFilters = { "login", "ishelf", "logout", "js", "css", "images", "img" };
		String uri = request.getRequestURI();
		
		logger.info("uri={}", uri);
		logger.info("content path={}", request.getContextPath());
		
		boolean beFilter = true;
		for (String s : noFilters) {
			if(uri.equals(request.getContextPath()+"/")){
				beFilter = false;
				break;
			}
			if (uri.indexOf(s) != -1) {
				beFilter = false;
				break;
			}
		}
		if (beFilter) {
			Object obj = request.getSession().getAttribute("username");
			if (null == obj) {

				// 未登录
				PrintWriter out = response.getWriter();
				StringBuilder builder = new StringBuilder();
				builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");
				builder.append("window.top.location.href=\"");
				builder.append(request.getContextPath());
				builder.append("/\";</script>");
				out.print(builder.toString());
				out.close();
				return false;
			} else {
				return true;
			}
		} else {
			return true;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

}
